package com.mzba.easy.weibo.ui;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.mzba.easy.weibo.BasicActivity;
import com.mzba.easy.weibo.R;
import com.mzba.easy.weibo.db.UserEntry;
import com.mzba.easy.weibo.db.UserGson;
import com.mzba.easy.weibo.util.AppContext;
import com.mzba.easy.weibo.util.UICore;
import com.mzba.easy.weibo.util.WeiboManager;
import com.mzba.easy.weibo.widget.CustomListView;
import com.mzba.easy.weibo.widget.RemoteImageView;
/**
 * 
 * @author 06peng
 *
 */
public class ChooseFriendActivity extends BasicActivity implements Callback {

	private final int get_friends = 1;
	private final int search_friends = 2;
	private final int menu_confirm = 3;
	private final int load_more = 4;
	
	private ActionBar actionBar;
	private CustomListView listView;
	private EditText searchView;
	
	private Handler handler;
	private List<UserEntry> friendList;
	private List<UserEntry> results;
	private Set<String> usernameSet;
	private WeiboManager weiboManager;
	private FriendListAdapter adapter;
	private int count = 20;
	private int cursor = 0;
	
	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.choose_friend_list);
		handler = new Handler(this);
		actionBar = getSupportActionBar();
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setDisplayShowHomeEnabled(false);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setTitle("选择要@的好友");
        
        listView = (CustomListView) findViewById(R.id.choose_friend_listview);
        listView.setonRefreshListener(new CustomListView.OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				cursor = 0;
				UICore.eventTask(ChooseFriendActivity.this, ChooseFriendActivity.this, get_friends, null, null);
			}
		});
        listView.setonLoadListener(new CustomListView.OnLoadListener() {
			
			@Override
			public void onLoad() {
				UICore.eventTask(ChooseFriendActivity.this, ChooseFriendActivity.this, load_more, null, null);
			}
		});
        searchView = (EditText) findViewById(R.id.choose_friend_search);
        searchView.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				 UICore.eventTask(ChooseFriendActivity.this, ChooseFriendActivity.this, search_friends, null, null);
			}
		});
        usernameSet = new HashSet<String>();
        weiboManager = new WeiboManager(this);
        UICore.eventTask(this, this, get_friends, "", null);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, menu_confirm, 0, "确定").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case menu_confirm:
			Intent intent = new Intent();
			if (usernameSet != null && !usernameSet.isEmpty()) {
				String[] friends = new String[usernameSet.size()];
				usernameSet.toArray(friends);
				intent.putExtra("friends", friends);
				setResult(RESULT_OK, intent);
			}
			finish();
			break;
		case android.R.id.home:
			finish();
			break;
		default:
			break;
		}
		return false;
	}
	
	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case get_friends:
			UserGson gson = weiboManager.getFriends(AppContext.getInstance().getUid(), count, cursor);
			friendList = gson.getUsers();
			cursor = gson.getNext_cursor();
			results = new ArrayList<UserEntry>(friendList);
			handler.sendEmptyMessage(get_friends);
			break;
		case search_friends:
			searchFriend();
			break;
		case load_more:
			UserGson gson2 = weiboManager.getFriends(AppContext.getInstance().getUid(), count, cursor);
			List<UserEntry> more = gson2.getUsers();
			cursor = gson2.getNext_cursor();
			friendList.addAll(more);
			results = new ArrayList<UserEntry>(friendList);
			handler.sendEmptyMessage(get_friends);
			break;
		default:
			break;
		}
	}
	
	private void searchFriend() {
		Set<UserEntry> newValues = new HashSet<UserEntry>();
		String str = searchView.getText().toString().trim();
		for (UserEntry entry : friendList) {
			if (entry.getScreen_name().indexOf(str) != -1) {
				newValues.add(entry);
			}
		}
		if (newValues.size() > 0) {
			results = new ArrayList<UserEntry>(newValues);
		} else {
			results = new ArrayList<UserEntry>(friendList);
		}
		handler.sendEmptyMessage(search_friends);
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case get_friends:
			if (results != null && !results.isEmpty()) {
				adapter = new FriendListAdapter();
				listView.setAdapter(adapter);
			}
			break;
		case search_friends:
			adapter.notifyDataSetChanged();
			break;
		case load_more:
			adapter.notifyDataSetChanged();
			listView.setSelection(results.size() - count);
			listView.onLoadComplete();
			break;
		default:
			break;
		}
		return false;
	}
	
	public class FriendListAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return results.size();
		}

		@Override
		public Object getItem(int arg0) {
			return results.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.choose_friend_item, null);
				holder.avatarView = (RemoteImageView) convertView.findViewById(R.id.choose_friend_item_avatar);
				holder.usernameView = (TextView) convertView.findViewById(R.id.choose_friend_item_username);
				holder.checkbox = (CheckBox) convertView.findViewById(R.id.choose_friend_item_checkbox);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			try {
				final UserEntry entry = results.get(position);
				if (entry != null) {
					holder.usernameView.setText(entry.getScreen_name());
					holder.avatarView.setImageUrl(entry.getProfile_image_url(), AppContext.USERHEADICON, position, listView);
					holder.checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
						
						@Override
						public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
							if (isChecked) {
								usernameSet.add(entry.getScreen_name());
							} else {
								usernameSet.remove(entry.getScreen_name());
							}
						}
					});
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return convertView;
		}
	}
	
	public static class ViewHolder {
		RemoteImageView avatarView;
		TextView usernameView;
		CheckBox checkbox;
	}
}
